import ContentCard from "@/components/card"
import { App, Button, Input, Space, Table } from "antd"
import { PlusOutlined } from '@ant-design/icons'
import WorkplaceForm, { type WorkplaceRef } from "./WorkplaceForm"
import { useEffect, useRef, useState } from "react"
import useFindData from "@/hooks/useFindData"
import { deleteWorkplaceApi } from "@/apis/workplaceApi"

const Workplace = () => {
    const formRef = useRef<WorkplaceRef>(null);
    const { findWorkplaceHook, workplaceData } = useFindData();

    // const [checkedIds, setCheckedIds] = useState([])
    // let checkedIds: React.Key[] = [];
    const checkedIds = useRef<React.Key[]>([])

    const { message } = App.useApp();

    const columns = [
        {
            title: '所在城市', dataIndex: 'city',
            render: (city: string[]) => city.join('>')
        },
        {
            title: '组织类型', dataIndex: ['organizationTypeId', 'name'],
        },
        {
            title: '操作', dataIndex: '_id',
            render: (_id: string, item: any) => (
                <Space>
                    <a onClick={() => {
                        formRef.current!.openModal(item);
                    }}>编辑</a>
                    <a>删除</a>
                </Space>
            )
        }
    ]

    useEffect(() => {
        findWorkplace();
    }, [])

    const findWorkplace = () => {
        findWorkplaceHook();
    }

    const onCheckboxChange = (selectedRowKeys: React.Key[]) => {
        checkedIds.current = selectedRowKeys;
    }

    const onDeleteChecked = () => {
        if (checkedIds.current.length == 0) {
            message.warning('请先勾选要删除的数据');
        } else {
            deleteWorkplaceApi({ _id: checkedIds.current })
                .then(res => {
                    console.log(res);
                })
        }
    }

    return (
        <>
            <ContentCard title="工作地点">
                <div className="flex-bt">
                    <Input.Search style={{ width: 300 }} enterButton />

                    <Space>
                        <Button type="primary" icon={<PlusOutlined />} onClick={() => {
                            formRef.current!.openModal();
                        }}>新增工作地点</Button>
                        <Button onClick={onDeleteChecked}>批量删除</Button>
                    </Space>
                </div>

                <Table dataSource={workplaceData.rows} columns={columns} rowKey="_id"
                    rowSelection={{ onChange: onCheckboxChange }} />
            </ContentCard>

            <WorkplaceForm ref={formRef} />
        </>
    )
}

export default Workplace